package com.arlen.centre.service.impl;

import com.alibaba.fastjson.JSON;
import com.arlen.centre.service.WxAccessToken;
import com.arlen.centre.service.WxMenuService;
import com.arlen.common.constant.GetHttpConstant;
import com.arlen.common.result.Result;
import com.arlen.common.vo.Menu;
import com.arlen.until.http.Interaction;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.io.IOException;


@Service
public class WxMenuServiceImpl implements WxMenuService {


    private static final String CREATE_MENU = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";

    @Autowired
    WxAccessToken wxAccessToken;

    @Autowired
    Interaction interaction;


    @Override//微信创建菜单的服务
    public Result createMenu(Menu menu, String appId, String appSecret) throws IOException {
        if (StringUtils.isBlank(appId) && StringUtils.isBlank(appSecret) && ObjectUtils.isArray(menu)) {
            return new Result(Result.ERROR);
        }
        String menuJson = JSON.toJSONString(menu);


        Result accessToken = wxAccessToken.getAccessToken(appId, appSecret);
        if (accessToken.getResult().equals(Result.ERROR)) {
            return accessToken;
        }

        String urlAppId = CREATE_MENU.replace("ACCESS_TOKEN", accessToken.getData().toString());
        //发送post请求
        boolean b = interaction.sendPost(urlAppId, menuJson);

        return null;
    }

    private static final String DEL_MENU ="https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";



    @Override //删除
    public Result delMenu(String appId, String appSecret) throws IOException {
        if (StringUtils.isBlank(appId) && StringUtils.isBlank(appSecret)) {
            return new Result(Result.ERROR);
        }
        Result accessToken = wxAccessToken.getAccessToken(appId, appSecret);
        if (accessToken.getMsg().equals(Result.ERROR)){
            return new Result(Result.ERROR);
        }
        String access_token = interaction.sendGet(DEL_MENU.replace("ACCESS_TOKEN", accessToken.getData().toString()), GetHttpConstant.NOANALYSIS.getState());
        if (access_token!=null){
            return new Result(Result.SUCCESS);
        }
        return new Result(Result.ERROR);
    }
}
